<template>
	<div class="dialog-body" ref="dialogBody" :class="{'client-list-hide': !showClientList}">
		<div class="dialog-msg-list">
			<!-- <div class="show-more-history">
				查看更多历史消息
			</div> -->
			<div
				v-for="(item, index) of clientDialogList" :key="index"
				class="msg-item-wrap">
				<!--消息时间-->
				<div v-show="showTime(index)" class="msg-send-time">
					{{$public.dateFormat(item.create_time)}}
				</div>
				<div class="row" :class="{client: item.message_type === '1', adviser:  item.message_type === '2'}">
					<!--代理人-->
					<div v-if="item.message_type === '2'" class="msg-item-emotion">
						<div class="msg-item adviser">
							<img :src="adviserRoundImg"  class="header-img adviser"/>
							<!--名片-->
							<calling-card-item v-if="item.message_body_type === 'callingCard'" :isChat="true"></calling-card-item>
							<!--视频类型项-->
							<video-card-item v-else-if="item.message_body_type === 'videoCard'" :isChat="true" :item="item"></video-card-item>
							<!--建议书、保障检视等h5页面-->
							<page-card-item v-else-if="item.message_body_type === 'pageUrl'" :isChat="true" :item="item"></page-card-item>
							<!--普通文本-->
							<div v-else class="msg adviser" v-html="item.message.content.replace(/\n/g, '<br />')"></div>
						</div>
					</div>
					<!--客户-->
					<div v-else class="msg-item-emotion">
						<div class="msg-item">
							<div class="msg-item client">
								<img :src="currentClientInfo.gender === 'M' ? maleRoundImg : femaleRoundImg"  class="header-img client"/>
								<div class="msg" v-html="item.message.content"></div>
							</div>
						</div>
						<!--客户情绪-->
						<div v-if="item.emotion === '负面' || item.emotion === '正面'"  class="client-emotion">
							<svg-icon v-if="item.emotion === '负面'" icon-class="warning" class="warning"></svg-icon>
							<svg-icon v-if="item.emotion === '正面'" icon-class="tick" class="tick"></svg-icon>
							<span class="client-emotion-item" 
								:class="{
									'green': item.emotion === '正面',
									'red': item.emotion === '负面'
								}">
								客户情绪：【{{item.emotion}}】【{{item.emotion_item}}】
							</span>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { mapState, mapMutations } from "vuex"
import mockImg from '@/assets/images/calling-card.png'
import CallingCardItem from '@/components/lm-chat/lm-dialogue-panel/components/calling-card-item.vue'
import PageCardItem from '@/components/lm-chat/lm-dialogue-panel/components/page-card-item.vue'
import VideoCardItem from '@/components/lm-chat/lm-dialogue-panel/components/video-card-item.vue'
import adviserRoundImg from '@/assets/images/adviser-round.png'
import femaleRoundImg from '@/assets/images/female-round.png'
import maleRoundImg from '@/assets/images/male-round.png'
export default {
	name: 'Dialogbody',
	components: {
		CallingCardItem,
		PageCardItem,
		VideoCardItem,
	},
	data() {
		return {
			mockImg,
			adviserRoundImg,
			femaleRoundImg,
			maleRoundImg,
			adviserSocket: null,
			adviserHeartCheck: {
				// timeout: 50000, // 50，秒发一次心跳
				timeout: 25000, // 25秒发一次心跳
				timeoutObj: null
			},
			reconnectAttempts: 0, // 重连尝试次数
			maxReconnectAttempts: 5, // 最大重连尝试次数
			reconnectInterval: 1000, // 初始重连间隔时间，单位毫秒
			needReconnect: true, // 是否需要重连
			agent_name: LOCAL_CONFIG.agent_name,
		}
	},
	computed: {
		...mapState('lm-chat', ['currentSessionInfo', 'clientDialogList', 'currentClientId',
		 'currentClientInfo', 'scrollDialogMessage', 'showClientList']),
		// curDialogMsgList() {
		// 	return this.clientDialogInfoMap[this.currentClientId] || []
		// }
	},
	watch: {
		scrollDialogMessage(val) {
			if (val) {
				this.scrollToBottom()
				this.setScrollDialogMessage(false)
			}
		}
	},
	mounted() {
		this.needReconnect = true
		this.createAdviserSocket()
	},
	beforeDestroy() {
		this.needReconnect = false
		if(this.adviserSocket) {
			this.adviserSocket.close()
		}
	},
	activated() {
		this.scrollToBottom()
	},
	methods: {
		...mapMutations('lm-chat', ['seCurrentSessionInfo', 'setScrollDialogMessage', 'pushDialogMessage', 
		'setClientLastMsgItem', 'updateRecognitionModuleInfo', 'updateDialogMessageEmotion']),
		// 滚动到底部
		scrollToBottom() {
			let dialogBody = this.$refs.dialogBody
			dialogBody.scroll({
				top: dialogBody.scrollHeight,
				// behavior: 'smooth'
			})
		},
		// 判断是否显示消息时间
		showTime(index) {
			if (index === 0) return true
			if (!this.clientDialogList[index].create_time) return false
			let curTime = this.clientDialogList[index].create_time
			let preTime = this.clientDialogList[index - 1].create_time
			return curTime - preTime >= 5 * 60 * 1000
		},
		// 创建websocket
		createAdviserSocket () {
			if (typeof WebSocket === 'undefined') {
				console.log('您的浏览器不支持WebSocket')
			} else {
				console.log('您的浏览器支持WebSocket')
				if (this.adviserSocket !== null) {
					this.adviserSocket.close()
					this.adviserSocket = null
					clearTimeout(this.adviserHeartCheck.timeoutObj)
				}
				this.adviserSocket = new WebSocket(LOCAL_CONFIG.adviserWs)
				// 打开事件
				this.adviserSocket.onopen = () => {
					console.log('代理人websocket已打开')
					this.startHeartCheck() // 心跳检测重置
					console.log('代理人websocket连接成功!' + new Date().toLocaleString())
				}
				// 获得消息事件
				this.adviserSocket.onmessage = msg => {
					this.startHeartCheck() // 如果获取到消息，心跳检测重置
					let msgData = JSON.parse(msg.data)
					if (msgData.data) {
						let data = msgData.data
						let item = {
							clientId: data.clientId,
							message_type:  data.msgSide || '1', // message_type 1.用户->代理人 2.代理人->用户 3.代理人->大模型 4.大模型->代理人
							message_body_type: data.aiccMsgType,
							create_time: data.createTime || '',
							message: {},
							emotion: '',
							emotion_item: '',
							msgId: data.msgId
						}
						item.message = data.aiccMsgContent
						if(data.aiccMsgType === 'emotion') {
							if(data.aiccMsgContent.emotion === '正面' || data.aiccMsgContent.emotion === '负面') {
								this.updateRecognitionModuleInfo({
									moduleName: 'emotionInfo',
									moduleData: {
										emotion: data.aiccMsgContent.emotion,
										emotion_item: data.aiccMsgContent.emotionItem
									}
								})
								this.updateDialogMessageEmotion({
									clientId: data.clientId,
									msgId: data.msgId,
									emotion: data.aiccMsgContent.emotion,
									emotion_item: data.aiccMsgContent.emotionItem
								})
							}
						} else {
							this.pushDialogMessage(item)
							this.setClientLastMsgItem(item)
						}
						this.$nextTick(() => {
							this.setScrollDialogMessage(true)
						})
					}
				}
				// 关闭事件
				this.adviserSocket.onclose = () => {
					console.log('代理人websocket已关闭' + new Date().toLocaleString())
					this.needReconnect && this.reconnectWebSocket(); // 添加断线重连逻辑
				}
				// 发生了错误事件
				this.adviserSocket.onerror = function () {
					console.log('代理人websocket发生了错误' + new Date().toLocaleString())
				}
			}
		},
		startHeartCheck () {
			clearTimeout(this.adviserHeartCheck.timeoutObj)
			this.adviserHeartCheck.timeoutObj = setTimeout(() => {
				// 这里发送一个心跳，后端收到后，返回一个心跳消息，
				// onmessage拿到返回的心跳就说明连接正常
				this.adviserSocket.send('2')
			}, this.adviserHeartCheck.timeout)
		},
		// 新增重连方法
		reconnectWebSocket() {
			if (this.reconnectAttempts < this.maxReconnectAttempts) {
				console.log(`代理人websocket尝试重新连接，当前尝试次数：${this.reconnectAttempts}`);
				setTimeout(() => {
					this.createAdviserSocket(); // 尝试重新创建WebSocket连接
					this.reconnectAttempts++; // 重连次数加一
					// 可选：逐渐增加重连间隔
					// this.reconnectInterval = this.reconnectInterval * 2;
				}, this.reconnectInterval);
			} else {
				this.$public.message(this, 'error', '当前用户已登录')
				console.error('代理人websocket达到最大重连次数，不再尝试重连');
				this.reconnectAttempts = 0; // 重置重连次数，以便下次连接时重新计算
				this.adviserSocket = null; // 确保状态正确
			}
		},
	}
}
</script>

<style lang="scss" scoped>
.dialog-body{
	height: 100%;
	overflow: hidden auto;
	overflow-y: overlay;
	padding: 20px 284px 0px 20px;
	position: relative;
	&.client-list-hide{
		padding-right: 20px;
	}
	.show-more-history{
		cursor: pointer;
    color: #999;
    text-align: center;
    margin-bottom: 8px;
	}
	.msg-item-wrap{
		.msg-send-time{
			color: #9B9B9B;
			text-align: center;
			line-height: 1;
			margin: 5px 0;
		}
		.row{
			display: flex;
			padding: 15px 0;
			&.adviser{
				justify-content: flex-end;
			}
			.msg-item-emotion{
				max-width: calc(100% - 40px);
				.msg-item{
					display: flex;
					&.adviser{
						flex-direction: row-reverse;
					}
					.header-img{
						width: 30px;
						height: 30px;
						margin-right: 10px;
						&.adviser{
							margin-left: 10px;
							margin-right: 0px;
						}
					}
					.msg{
						background: #fff;
						border: 1px solid #E3E3E3;
						border-radius: 4px;
						padding: 8px 12px;
						line-height: 18px;
						color: #434343;
						&.adviser{
							border: 0;
							background: #4686F2;
							color: #fff;
						}
					}
					.client-emotion{
						color: #ff9722;
						display: flex;
						align-items: center;
						margin-top: 10px;
						.warning{
							width: 14px;
							height: 12px;
						}
						.tick{
							width: 12px;
							height: 12px;
						}
						.client-emotion-item{
							margin-left: 5px;
							&.red{
								color: #CD0808;
							}
							&.green{
								color: #41AD3C;
							}
						}
					}
					/deep/ .lm-chatgpt-item{
						.chatgpt-item-content{
							padding: 20px;
							border-radius: 8px;
							background: #fff;
							.item-section-title{
								font-size: 14px;
								font-weight: bold;
								line-height: 1;
							}
						}
					}
				}
			}
		}
	}
}
</style>